<?php

namespace App\Models\Member;

use App\Models\BaseModel;
use App\Models\Member\Order;
use App\Models\Member\Share;
use App\Models\Member\Store;
use DB;

class OrderItem extends BaseModel
{
    protected $fillable = [
        'id', 'order_id', 'good_id', 'base_price',
        'pay_price', 'jf', 'good_title', 'good_logo', 'goods_quantity', 
        'created_at', 'updated_at'
    ];
    public function getWeightArr($weightArr, $value, $num)
    {
        $weight = $value['weight']*$num;// 总重量
        switch ($value['is_delivery_fee']) {
            case 1:
                # 免邮
                $weightArr['freeExp'] += $weight;
                break;
            case 2:
                # 不免邮 且 不分单
                $weightArr['exp'] += $weight;
                break;
            case 3:
                # 不免邮 且 分单
                $weightArr = $this->expFen($weightArr, $value, $num, $weight);
                break;
            case 4:
                # 不免邮 且 单独算一单
                $weightArr = $this->expSole($weightArr, $value, $num, $weight);
                break;
            default:
                # 非法值
                break;
        } 
        return $weightArr;
    }

    // 不免邮 且 单独算一单
    public function expSole($weightArr, $value, $num, $weight)
    {
        $fen = 1;
        $list_num = empty($value['list_num']) ? 100 : $value['list_num'];
        if ($num >= $value['list_num']) {
            $weightFen = $value['weight'] * $list_num;// 每个分单的重量
            $fen = floor($num / $value['list_num']);// 分单数目
            $weightFenYu = $weight - $weightFen * $fen;// 分单之后的余单重量
            $weightArr['expSole'][$value['id']]['weight'] = $weightFen;
            $weightArr['expSole'][$value['id']]['listNum'] = $fen;
            $weightArr['expSoleYu'][$value['id']]['weight'] = $weightFenYu;
            $weightArr['expSoleYu'][$value['id']]['listNum'] = 1;
        } else {
            $weightArr['expSole'][$value['id']]['weight'] = $weight;
            $weightArr['expSole'][$value['id']]['listNum'] = $fen;
        }
        return $weightArr;
    }

    // 不免邮 且 分单
    public function expFen($weightArr, $value, $num, $weight)
    {
        $fen = 1;
        $list_num = empty($value['list_num']) ? 100 : $value['list_num'];
        if ($num >= $value['list_num']) {
            $weightFen = $value['weight'] * $list_num;// 每个分单的重量
            $fen = floor($num / $value['list_num']);// 分单数目
            $weightFenYu = $weight - $weightFen * $fen;// 分单之后的余单重量
            $weightArr['expFen'][$value['id']]['weight'] = $weightFen;
            $weightArr['expFen'][$value['id']]['listNum'] = $fen;
            $weightArr['exp'] += $weightFenYu;
        } else {
            $weightArr['exp'] += $weight;
        }
        return $weightArr;
    }

    // 得出订单详情 和 支付总价 - 商品信息/价格阶梯/购物车信息/价格等级
    public function setOrderItem($goodsData, $priceArr, $info, $level, $user, $orderInfo)
    {
        $item = [];
        $var = 0;
        $costPrice = 0;// 成本价格
        $payPrice = 0;// 支付价格
        $jf_up = 0;// 抵扣上限
        $weightArr = [];
        $weightArr['freeExp'] = 0;
        $weightArr['exp'] = 0;
        $weightArr['expFen'] = [];
        $weightArr['expSole'] = [];
        $weightArr['expSoleYu'] = [];// 不免邮 且 单独算一单 分单之后 剩余的产品 依旧单独算作一单
        $jfUp = 0;

        $shareModel = new Share;
        $shareData = $shareModel->storeShare($user['store_id']);

        foreach ($goodsData as $key => $value) {
            $pitch = $info[$value['id']]['pitch'];// 只处理 选择的商品
            if ($pitch) {
                $num = $info[$value['id']]['num'];
                $weightArr = $this->getWeightArr($weightArr, $value, $num);
                $item[$key]['order_id'] = &$var;
                $item[$key]['good_id'] = $value['id'];
                $item[$key]['base_price'] = $value['base_price'];
                $item[$key]['jf'] = $value['jf_send'];
                $item[$key]['good_title'] = $value['title'];
                $item[$key]['good_describe'] = $value['describe'];
                $item[$key]['good_logo'] = $value['cover'];
                
                $item[$key]['share_gold'] = ($shareData->type == 3 && $shareData->method == 1) ? $value['share_gold'] : $value['share_money'];
                $item[$key]['pay_price'] = $priceArr[$value['id']][$level]['price']*100;
                $item[$key]['goods_quantity'] = $num;
                $item[$key]['created_at'] = date('Y-m-d H:i:s');
                
                $costPrice +=  $value['cost'] * $item[$key]['goods_quantity'];
                $payPrice +=  $item[$key]['pay_price'] * $item[$key]['goods_quantity'];
                $jfUp += $value['jf']*$item[$key]['goods_quantity'];
            }
        }
        $store = new Store;
        $storeInfo = $store->where('id',$user['store_id'])->first();
        $orderInfo['cost_price'] = $costPrice;
        $orderInfo['pay_price'] = $payPrice;
        $orderInfo['jf_price'] = $user['jf'] > $jfUp*$storeInfo['ratio'] ? $jfUp : intdiv($user['jf']/100,$storeInfo['ratio'])*100;
        $orderInfo['express_weight'] = json_encode($weightArr);
        return $this->orderEnd($var, $user, $orderInfo, $item);
    }

    // 获取 订单 积分使用上限
    public function getUseJf($id, $user)
    {
        $goodsData = $this->join('goods as g', 'order_items.good_id', '=', 'g.id')
        ->where("order_items.order_id",$id)
        ->select('g.id', 'g.jf', 'order_items.goods_quantity')
        ->get()->toArray();
        $jfUp = 0;
        foreach ($goodsData as $key => $value) {
            $jfUp += $value['jf'] * $value['goods_quantity'];
        }

        $store = new Store;
        $storeInfo = $store->where('id',$user['store_id'])->first();
        $jfUp = $user['jf'] > $jfUp*$storeInfo['ratio'] ? $jfUp : intdiv($user['jf']/100,$storeInfo['ratio'])*100;
        return $jfUp;
    }

    // 获取 订单分享金额总额
    public function getShareGold($id)
    {
        $goodsData = $this->where('order_id', $id)->select('goods_quantity', 'share_gold')
        ->get()->toArray();

        $shareGold = 0;
        foreach ($goodsData as $key => $value) {
            if(is_array(json_decode($value['share_gold'],true))){
                $shareGold += array_sum(json_decode($value['share_gold'],true)) * $value['goods_quantity'];
            }else{
                $shareGold += $value['share_gold'] * $value['goods_quantity'];
            }
        }
        return $shareGold*100;
    }
    // 引用传值 保证 订单详情中对应的订单id的变化
    public function orderEnd(&$var, $user, $orderInfo, $item)
    {
        $Order = new Order;
        DB::beginTransaction();
        try {
            $orderId = $Order->setOrder($user, $orderInfo);
            if ($orderId) {
                $var = $orderId;
                $orderItem = $this->insert($item);
                if ($orderItem) {
                    DB::commit();
                    return $this->successClient($var, '购物车数据提交成功');
                }else{
                    return $this->errorClient($orderInfo, '购物车订单详情插入失败');
                }
            }else{
                return $this->errorClient($orderInfo, '购物车订单信息插入失败');
            }
        } catch (\Exception $e) {
            DB::rollBack();
            return $e->getLine().$e->getMessage();
        }
    }

    // 获取指定id的订单详情信息
    public function getOrderItem($id)
    {
        return $this->where('order_id', $id)->get()->toArray();
    }

    //分享经济 来源为商品 方式为推荐关系 每一代获取金额
    public function shareLevelGold($orderId,$dai){
        $goodsData = $this->where('order_id', $orderId)->select('goods_quantity', 'share_gold')
        ->get()->toArray();

        $goldSum = 0;
        foreach ($goodsData as $key => $value) {
            $share_gold = json_decode($value["share_gold"],true);
            $gold = $share_gold[$dai];
            $goldSum += $gold * $value["goods_quantity"]; 
        }

        return $goldSum*100;
    }
}
